package com.adcc.ags.gms.core.controller;

import com.adcc.ags.gms.core.entity.SysUser;
import com.adcc.ags.gms.core.service.LoginService;
import com.adcc.ags.gms.core.util.Constant;
import com.adcc.ags.gms.core.util.LogFactory;
import com.google.common.base.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import javax.servlet.http.HttpSession;

/**
 * 系统登录控制层
 */
@Controller
public class LoginController {

    @Autowired
    private LoginService loginService;

    @Autowired
    private LogFactory log;

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public ModelAndView login(SysUser user, HttpSession session) {
        ModelAndView view = new ModelAndView();
        try {
            Optional<ModelAndView> optional = loginService.verifyUser(user, session);
            if (optional.isPresent()) {
                view = optional.get();
                if(session.getAttribute("user")!=null) {
                    //登陆成功后重定向首页面
                    view.setView(new RedirectView("/GMS/load"));
                }else{
                    //跳转登录页面
                    view.setViewName("/login/login");
                }
            } else {
                view.addObject("error", Constant.GMS_DB_ERROR);
                view.setViewName("/login/login");
            }
        } catch (Exception ex) {
            log.error(LoginController.class, "login() error", ex);
            view.addObject("error", Constant.GMS_SERVER_ERROR);
            view.setViewName("/login/login");
        }
        return view;
    }

}
